package com.wclass.oss;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * 七牛云存储
 */
public class QiniuCloudStorageService extends CloudStorageService {

    private UploadManager uploadManager;
    private String token;

    //七牛绑定的域名
    private String qiniuDomain = "http://pkbmq486r.bkt.clouddn.com";
    /**
     * 七牛accessKey
     */
    @Value("${qiniu.accessKey}")
    private String accessKey;
    /**
     * 七牛secretKey
     */
    @Value("${qiniu.secretKey}")
    private String secretKey;
    /**
     * 七牛空间
     */
    @Value("${qiniu.hubName}")
    private String hubName;
    //七牛存储空间名
    private String qiniuBucketName = "upload";

    public QiniuCloudStorageService() {
        //初始化
        init();
    }

    private void init() {
        uploadManager = new UploadManager(new Configuration(Zone.autoZone()));
        token = Auth.create(accessKey, secretKey).
                uploadToken(qiniuBucketName);
    }

    @Override
    public String upload(MultipartFile file) throws Exception {
        String fileName = file.getOriginalFilename();
        String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
        return upload(file.getBytes(), getPath(hubName) + "." + prefix);
    }

    @Override
    public String upload(byte[] data, String path) {
        try {
            Response res = uploadManager.put(data, path, token);
            if (!res.isOK()) {
                throw new RuntimeException("上传七牛出错：" + res.toString());
            }
        } catch (Exception e) {
            throw new RuntimeException("上传文件失败，请核对七牛配置信息", e);
        }

        return qiniuDomain + "/" + path;
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            byte[] data = IOUtils.toByteArray(inputStream);
            return this.upload(data, path);
        } catch (IOException e) {
            throw new RuntimeException("上传文件失败", e);
        }
    }

    @Override
    public void delete(String path){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());

        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(qiniuBucketName, path);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            throw new RuntimeException("删除文件失败", ex);
        }
    }
}
